package com.clound.order.controller;

import com.clound.order.Service.OrderService;
import com.clound.order.VO.ResultVO;
import com.clound.order.converter.OrderForm2DTO;
import com.clound.order.dto.OrderDTO;
import com.clound.order.enums.ResultEnum;
import com.clound.order.exception.OrderException;
import com.clound.order.form.OrderForm;
import com.clound.order.utils.ResultVOUtils;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import javax.validation.Valid;

/**
 * Created by zzy on 2018/4/7.
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     * @param orderForm
     * @param bindingResult
     * @return
     */
    @PostMapping("/create")
    public ResultVO create(@Valid OrderForm orderForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new OrderException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
       OrderDTO orderDTO= OrderForm2DTO.convert(orderForm);
        //判断购物车信息是否为空
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            throw new OrderException(ResultEnum.CART_ENPTY);
        }
        orderService.createOrder(orderDTO);
        Map<String,Object> data= Maps.newHashMap();
        data.put("orderId",orderDTO.getOrderId());
        return ResultVOUtils.success(data);
    }
}
